/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isInLeft(TreeNode* root,TreeNode* p)
    {
        if(root==nullptr) return false;
        return root==p || isInLeft(root->left,p) || isInLeft(root->right,p);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==p || root==q) return root;

        bool pInLeft = isInLeft(root->left,p);
        bool pInRight = !pInLeft;

        bool qInLeft = isInLeft(root->left,q);
        bool qInRight = !qInLeft;

        if((qInLeft&&pInRight)||(qInRight&&pInLeft))
        {
            return root;
        }
        else if(qInLeft&&pInLeft)
        {
            return lowestCommonAncestor(root->left,p,q);
        }
        else{
            return lowestCommonAncestor(root->right,p,q);
        }
    }
};